package com.kchouse.mine;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.MineAddressItem;
import com.kchouse.bean.MineCarItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;

import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class MineAddressActivity extends BaseActivity implements View.OnClickListener {

    private MineAddressActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private ListView lv_item;
//    private TextView tv_management;
    private boolean isShowDel = false;//是否显示删除按钮
    private AddAdapter adapter;
    private Button bt_add;
    private Intent intent;
    private ArrayList<MineAddressItem> listaddress=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_address);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("我的地址");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
//        tv_management = (TextView) findViewById(R.id.tv_management);
//        tv_management.setOnClickListener(this);
        bt_add = (Button) findViewById(R.id.bt_add);
        bt_add.setOnClickListener(this);

        lv_item = (ListView) findViewById(R.id.lv_item);
        adapter = new AddAdapter();
        lv_item.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        GetMineAddress();
    }

    private void intiData() {

        intent=getIntent();

//        GetMineAddress();
    }

    /**
     * 获取我的地址列表
     */
    private void GetMineAddress() {
        String url = API.GetMineAddress + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    listaddress.clear();
                    listaddress.addAll(JSONObject.parseArray(data.getString("addressList"), MineAddressItem.class));
                    adapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_add:
                intent.setClass(mContent,NewAddressActivity.class);
                startActivity(intent);
                break;
//            case R.id.tv_management:
//                if (isShowDel) {
//                    isShowDel = false;
//                } else {
//                    isShowDel = true;
//                }
//                adapter.notifyDataSetChanged();
//                break;
        }
    }

    class AddAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listaddress.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MineAddressItem item = listaddress.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_address_item, null);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(item.getName());
            TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);
            tv_phone.setText(item.getPhone());
            TextView tv_address = (TextView) view.findViewById(R.id.tv_address);
            tv_address.setText(item.getAddress());
            Button bt_del = (Button) view.findViewById(R.id.bt_del);
            bt_del.setOnClickListener(new DelOnClick(position));
//            rl_del.setOnClickListener(new DelOnClick(position));
//            if (isShowDel) {
//                rl_del.setVisibility(View.VISIBLE);
//            } else {
//                rl_del.setVisibility(View.GONE);
//            }

            return view;
        }
    }

    class DelOnClick implements View.OnClickListener {

        private int pos;

        public DelOnClick(int pos) {
            this.pos = pos;
        }

        @Override
        public void onClick(View v) {
            MineAddressItem item = listaddress.get(pos);
            showNormalDialog(item.getId());
//            ToastUtils.getInstanc(mContent).showToast("删除第" + (pos + 1) + "行");
        }
    }

    private void showNormalDialog(final String id){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mContent);
        normalDialog.setTitle("确认删除该地址？");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DelMineAdress(id);
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        // 显示
        normalDialog.show();
    }

    /**
     * 移除我的车辆
     */
    private void DelMineAdress(String id) {
        String url = API.DelMineAdress + id;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("id", id);
//        params.addFormDataPart("type", publishType);
        HttpRequest.delete(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    ToastUtils.getInstanc(mContent).showToast("删除成功");

                    GetMineAddress();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

}
